package app.hzvmap.com.rangecontrol.acitvity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import app.hzvmap.com.rangecontrol.App;
import app.hzvmap.com.rangecontrol.R;
import app.hzvmap.com.rangecontrol.acitvity.Base.AppCompatBaseActivity;
import app.hzvmap.com.rangecontrol.acitvity.Base.BaseActivity;
import app.hzvmap.com.rangecontrol.model.Division;
import app.hzvmap.com.rangecontrol.model.SmartCallBack;
import app.hzvmap.com.rangecontrol.utils.AppSetting;
import app.hzvmap.com.rangecontrol.utils.XUtil;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */

@ContentView(R.layout.activity_settings)
public class SettingsActivity extends BaseActivity {

    @ViewInject(R.id.et_server)
    TextView et_server;

    @ViewInject(R.id.et_divition)
    TextView et_divition;

    @ViewInject(R.id.lbl_title)
    TextView lbl_title;


    List<Division> provinces;

    Division selectDivistion;

    private ArrayList<ArrayList<Division>> citis = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<Division>>> divisions = new ArrayList<>();

    private boolean isTest = false;
    private int times = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (AppSetting.getAppSetting(this).APPSERVER.get() != null && AppSetting.getAppSetting(this).APPSERVER.get().trim().length() > 0) {
            App.REMOTEADD = new InetSocketAddress(AppSetting.getAppSetting(this).TRACKSERVER.get(), AppSetting.getAppSetting(this).TRACKPORT.get());
            Intent intent = new Intent(SettingsActivity.this, H5Activity.class);

            if (AppSetting.getAppSetting(this).ACCOUNT.get() != null && AppSetting.getAppSetting(this).ACCOUNT.get().trim().length() > 0) {
                intent.putExtra("url", AppSetting.getAppSetting(this).APPSERVER.get() + AppSetting.getAppSetting(this).APPHOME.get());
            } else {
                intent.putExtra("url", AppSetting.getAppSetting(this).APPSERVER.get() + AppSetting.getAppSetting(this).APPLOGIN.get());
            }

            startActivity(intent);
            finish();
        } else {
            initProvinces();
        }
    }

    @Event(value = R.id.btn_save,
            type = View.OnClickListener.class)
    private void onSave(View view) {
        Intent intent = new Intent(SettingsActivity.this, H5Activity.class);
        if (isTest) {
            intent.putExtra("url", "http://ty.ranfong.com/");
            startActivity(intent);
        } else {
            if (selectDivistion != null) {
                AppSetting.getAppSetting(this).APPSERVER.set(selectDivistion.getAppServer());
                AppSetting.getAppSetting(this).APPHOME.set(selectDivistion.getAppHome());
                AppSetting.getAppSetting(this).APPLOGIN.set(selectDivistion.getAppLogin());
                try {
                    AppSetting.getAppSetting(this).TRACKPORT.set(Integer.parseInt(selectDivistion.getTrackPort()));
                } catch (Exception e) {
                }
                AppSetting.getAppSetting(this).TRACKSERVER.set(selectDivistion.getTrackServer());
                App.REMOTEADD = new InetSocketAddress(AppSetting.getAppSetting(this).TRACKSERVER.get(), AppSetting.getAppSetting(this).TRACKPORT.get());
                intent.putExtra("url", AppSetting.getAppSetting(this).APPSERVER.get() + AppSetting.getAppSetting(this).APPLOGIN.get());
                startActivity(intent);
            }
        }
    }

    @Event(value = R.id.btn_change_server,
            type = View.OnClickListener.class)
    private void onChangeServer(View view) {
        showPickerView();
    }

    @Event(value = R.id.lbl_title,
            type = View.OnClickListener.class)
    private void onTest(View view) {
        times += 1;
        if (times >= 5) {
            isTest = true;
            Toast.makeText(this, "开启测试模式", Toast.LENGTH_LONG).show();
        }
    }

    private void initProvinces() {
        TextView msg = (TextView) dialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText("正在加载数据");
        dialog.show();
        XUtil.Get("http://app.newgis.cn/fwkw/fwkw_app.json", null, new SmartCallBack<List<Division>>() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onSuccess(List<Division> result) {
                super.onSuccess(result);
                if (result != null) {
                    provinces = result;
                    initJsonData();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }


            @Override
            public void onFinished() {
                super.onFinished();
                dialog.dismiss();
                showPickerView();
            }
        });
    }

    private void initJsonData() {//解析数据

        for (Division provice : provinces) {//遍历省份
            /**
             * 添加城市数据
             */
            citis.add((ArrayList<Division>) provice.getChildren());
            ArrayList<ArrayList<Division>> divisionList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (Division city : provice.getChildren()) {//遍历该省份的所有城市
                divisionList.add((ArrayList<Division>) city.getChildren());//添加该省所有地区数据
            }


            /**
             * 添加地区数据
             */
            divisions.add(divisionList);
        }
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = provinces.get(options1) + "-" +
                        citis.get(options1).get(options2).getName() + "-" +
                        divisions.get(options1).get(options2).get(options3).getName();
                et_divition.setText(tx);
                et_server.setText(divisions.get(options1).get(options2).get(options3).getAppServer());
                selectDivistion = divisions.get(options1).get(options2).get(options3);
            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(provinces, citis, divisions);//三级选择器
        pvOptions.show();
    }
}
